package com.shop.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.ex.ShoppingException;
import com.shop.user.Interceptor.GetUserInfoInterceptor;
import com.shop.user.mapper.AddressBookMapper;
import com.shop.user.po.AddressBook;
import com.shop.user.po.User;
import com.shop.user.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 地址管理 服务实现类
 * </p>
 *
 * @author banxia
 * @since 2023-02-22
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookMapper mapper;

    //循环注入，防止调用事务方法失效
    @Autowired
    private AddressBookService addressBookService;

    @Override
    public List<AddressBook> getAllAddress() {
        User user = GetUserInfoInterceptor.getUser();
        if (user==null){
            ShoppingException.ThrowShoppingException("用户未登录 或 登录过期");
        }
        Long uid = user.getId();
        if (uid==null){
            ShoppingException.ThrowShoppingException("用户未登录 或 登录过期");
        }
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,uid);
        List<AddressBook> adds = mapper.selectList(wrapper);
        return adds;
    }

    @Override
    @Transactional
    public void deleteAddress(Long id) {
        AddressBook addressBook = mapper.selectById(id);
        if (addressBook!=null && addressBook.getIsDefault()){
            //将最近地址修改为默认地址
            setLatelyDefaultAdd();
        }
        mapper.deleteById(id);
    }


    //添加新地址，若本身没有地址，那么就将最近的地址设置为默认地址
    @Override
    @Transactional
    public void addAddressBook(AddressBook address) {
        //查询是否存在“默认地址”，否则address就是默认地址
        List<AddressBook> allAddress = getAllAddress();
        if (allAddress.size()==0) address.setIsDefault(true);
        //插入地址
        if (address.getIsDefault()!=null && address.getIsDefault()){
            //修改其他地址为 非默认
            setNoDefaultAdd();
        }
        User user = GetUserInfoInterceptor.getUser();
        address.setUserId(user.getId());
        address.setCreateUser(user.getId());
        address.setCreateTime(new Date());
        address.setUpdateTime(new Date());
        address.setUpdateUser(user.getId());
        mapper.insert(address);
    }

    //将id地址设置为默认地址
    @Override
    @Transactional
    public void setDefaultAdd(Long id) {
        //（1）将所有的地址设置为非默认地址
        setNoDefaultAdd();
        //（2）修改为默认地址
        User user = GetUserInfoInterceptor.getUser();
        Long uid = user.getId();
        AddressBook t1=new AddressBook();
        //（4）设置该id为默认地址
        t1.setIsDefault(true);
        t1.setId(id);
        mapper.updateById(t1);
    }

    @Override
    public void editAddress(AddressBook addressBook) {
        addressBook.setIsDefault(null);
        User user = GetUserInfoInterceptor.getUser();
        addressBook.setUpdateTime(new Date());
        addressBook.setUpdateUser(user.getId());
        mapper.updateById(addressBook);
    }

    //将最近使用的地址设置为默认地址
    private void setLatelyDefaultAdd(){
        AddressBook addressBook=new AddressBook();
        addressBook.setIsDefault(true);
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByDesc(AddressBook::getUpdateTime);
        wrapper.last("limit 0,1");//取最后一条地址
        mapper.update(addressBook,wrapper);
    }

    //将所有地址设置为 “非默认”
    private void setNoDefaultAdd(){
        User user = GetUserInfoInterceptor.getUser();
        //（1）获取用户信息
        if (user==null) ShoppingException.ThrowShoppingException("用户未登录或登录过期");
        Long uid = user.getId();
        if (uid==null)  ShoppingException.ThrowShoppingException("用户未登录或登录过期");
        //（2）定义查询条件
        LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,uid);
        //（3）定义修改条件
        AddressBook t1=new AddressBook();
        t1.setIsDefault(false);//设置为非默认地址
        mapper.update(t1,wrapper);
    }


}
